//
//  HomeViewController.m
//  StandardizedProduct
//
//  Created by 宁宁 on 16/6/20.
//  Copyright © 2016年 ym. All rights reserved.
//

#import "HomeViewController.h"


#import "UINavigationBar+BackgroundColor.h"//导航栏渐变

#import "HomeCategroyModel.h"//model

#import "SearchView.h"//搜索框View
#import "HADirect.h"//轮播view

#import "HomeCategroyTableViewCell.h"//分类Cell
#import "CategroyCollectionViewCell.h"//分类CollectionCell
#import "RecommendTableViewCell.h"//推荐section1Cell
#import "HotBrandsTableViewCell.h"//热门潮牌图片Cell

#import "CategoryDetailViewController.h"//商城详情界面Controller
#import "SearchViewController.h"//搜索Controller


@interface HomeViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, HADirectActionDelegate>

@property (nonatomic, strong) HADirect *hadView;//轮播View

@property (nonatomic, strong) UITableView *myTableView;

@end

@implementation HomeViewController
{
    NSUserDefaults *_defaults;
    
    float _recommandCellHeight;
    float _hotBrandCellHeight;
    
    SearchView *_search;
    
    NSMutableArray *_categroyCollectionArray;
}


 static NSString *const HomeCategroyTableViewCellID = @"HomeCategroyTableViewCell";
 static NSString *const RecommendTableViewCellID = @"RecommendTableViewCell";
 static NSString *const HotBrandsTableViewCellID = @"HotBrandsTableViewCell";

 static NSString *const CategroyCollectionViewCellID = @"CategroyCollectionViewCell";

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    _search.hidden = NO;
    
    //导航栏透明
    UIImage *image = [[UIImage alloc] init];
    [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    //去掉黑线
    self.navigationController.navigationBar.shadowImage = image;
    
    //购物车数量
    _defaults = [NSUserDefaults standardUserDefaults];
    if ([_defaults objectForKey:@"UserName"]) {
        [self requestCartList];
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    _search.hidden = YES;
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}

- (void)viewDidLoad {
    [super viewDidLoad]; 
    
    
    //设置导航栏
    [self setNav];
    
    //设置TableView
    [self settingTableView];
    
    //添加搜索框
    [self createSearchBar];
    
    [self requestCategroy];
    
}
#pragma mark === 设置导航栏 ===
- (void)setNav{
    self.edgesForExtendedLayout = UIRectEdgeNone;
    UIBarButtonItem *back = [[UIBarButtonItem alloc] init];
    back.title = @"返回";
    self.navigationItem.backBarButtonItem = back;
}

#pragma mark === 添加搜索框 ===
- (void)createSearchBar{
    _search = [[[NSBundle mainBundle] loadNibNamed:@"SearchView" owner:nil options:nil] lastObject];
    _search.frame = CGRectMake(0, 20, SCREEN_WIDTH, 44);
    _search.backgroundColor = [UIColor clearColor];
    _search.imagebgView.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.7];
    [self.navigationController.view addSubview:_search];
    
    
    [_search.searchBarBtn addTarget:self action:@selector(jumpToSearchController) forControlEvents:UIControlEventTouchUpInside];
}
- (void)jumpToSearchController{
    SearchViewController *search = [[SearchViewController alloc] init];
    search.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:search animated:YES];
}

#pragma mark === 设置TableView ===
- (void)settingTableView{
    //设置轮播
    NSArray *arr = @[@"SYicon01_01",@"SYicon01_01",@"SYicon01_01",@"SYicon01_01",@"SYicon01_01"];
    self.hadView = [HADirect direcWithtFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.48 * SCREEN_WIDTH) ImageArr:arr];
    self.myTableView.tableHeaderView = self.hadView;
    _hadView.delegate = self;
    
    //注册自定义cell
    [_myTableView registerClass:[HomeCategroyTableViewCell class] forCellReuseIdentifier:HomeCategroyTableViewCellID];
//    [_myTableView registerClass:[RecommendTableViewCell class] forCellReuseIdentifier:RecommendTableViewCellID];
    [_myTableView registerNib:[UINib nibWithNibName:@"RecommendTableViewCell" bundle:nil] forCellReuseIdentifier:RecommendTableViewCellID];
    [_myTableView registerNib:[UINib nibWithNibName:@"HotBrandsTableViewCell" bundle:nil] forCellReuseIdentifier:HotBrandsTableViewCellID];
}

#pragma mark === 轮播Delegate ===
- (void)HADirectActionWithIndex:(NSInteger)index{
    NSLog(@"index = %ld", index);
}

#pragma mark === UITableViewDelegate ===
//section数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 2) {
        return 10;
    }return 1;
}
//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:
            return 200;
        case 1:
            return _recommandCellHeight;
        case 2:
            return _hotBrandCellHeight;
        default:
            return 0;
    }
}
//Reusable
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        HomeCategroyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HomeCategroyTableViewCellID];
        cell.categroyCollectionView.delegate = self;
        cell.categroyCollectionView.dataSource = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if (indexPath.section == 1){
        RecommendTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RecommendTableViewCellID];
        
        NSArray *imageArray = @[cell.TodayCommandImage0, cell.TodayCommandImage10, cell.TodayCommandImage11, cell.hotGoodsImage0, cell.hotGoodsImage10, cell.hotGoodsImage11, cell.hotGoodsImage2, cell.todayLowImage0, cell.todayLowImage10, cell.todayLowImage11, cell.todayLowImage12];
        for (UIImageView *imageview in imageArray) {
            imageview.backgroundColor = [UIColor colorWithRed:VALUE green:VALUE blue:VALUE alpha:1];
        }
        
        _recommandCellHeight = cell.view.frame.origin.y + cell.view.frame.size.height;
        
        NSArray *array = @[cell.moreTodayLow, cell.moreHotGoods, cell.moreHotBrand];
        
        //more
        for (UIButton *button in array) {
            [button addTarget:self action:@selector(jumpToCategroyDetail:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else{
        HotBrandsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HotBrandsTableViewCellID];
//        cell.image.image = [UIImage imageNamed:<#(nonnull NSString *)#>];
        cell.image.backgroundColor = [UIColor colorWithRed:VALUE green:VALUE blue:VALUE alpha:1];
        _hotBrandCellHeight = cell.image.frame.size.height;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}







#pragma mark === UICollectionViewDelegate ===
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _categroyCollectionArray.count;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((SCREEN_WIDTH - 20) / 6, (SCREEN_WIDTH - 20) / 5 + 20);
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CategroyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CategroyCollectionViewCellID forIndexPath:indexPath];
    HomeCategroyModel *model = _categroyCollectionArray[indexPath.item];
    cell.title.text = model.Name;
    cell.title.adjustsFontSizeToFitWidth = YES;
    cell.image.backgroundColor = APPCOLOR;
    return cell;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [self jumpToCategroyDetail:indexPath.item];
}

//导航栏颜色渐变
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat offset = scrollView.contentOffset.y;

    CGFloat alpha = offset / 250;
    [self.navigationController.navigationBar nn_setBackgroundColor:[UIColor colorWithRed:224/255.0 green:102/255.0 blue:78/255.0 alpha:alpha]];
}

#pragma mark === 跳转到商品分类详情页 ===
- (void)jumpToCategroyDetail:(NSInteger)index{
    CategoryDetailViewController *cate = [[CategoryDetailViewController alloc] init];
    HomeCategroyModel *model = _categroyCollectionArray[index];
    cate.index = model.Id;
    cate.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:cate animated:YES];
}

- (UITableView *)myTableView{
    if (!_myTableView) {
        self.myTableView= [[UITableView alloc]initWithFrame:CGRectMake(0, - 64, SCREEN_WIDTH, SCREEN_HEIGHT - 44)style:UITableViewStylePlain];
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
        _myTableView.separatorColor = [UIColor clearColor];
        _myTableView.showsVerticalScrollIndicator = NO;//去掉滑动竖条
        
        [self.view addSubview:_myTableView];
    }
    return _myTableView;
}


#pragma mark === 网络请求 ===
- (void)requestCategroy{
    
    _categroyCollectionArray = [NSMutableArray array];
    
    [NetWorkManager requestWithType:HttpRequestTypeGet withMethodName:@"7494/api/Product/GetCateDt?" withParaments:nil withSuccessBlock:^(NSDictionary *object) {
        NSLog(@"商品类目 : %@", object);
        if ([object[@"Code"] isEqualToString:@"0"]) {
            for (NSDictionary *dic in object[@"Rows"]) {
                HomeCategroyModel *model = [HomeCategroyModel parseUserWithDictionary:dic];
                [_categroyCollectionArray addObject:model];
            }
            [_myTableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
        }
        
        
    } withFailureBlock:^(NSError *error) {
        NSLog(@"商品类目网络请求失败 : %@", error);
    } progress:nil];
    
}

//购物车数量
- (void)requestCartList{
    //列表
    NSDictionary *paraments = @{
                                @"userName"   : [_defaults objectForKey:@"UserName"],
                                @"cKeys"      : @"",
                                @"pageIndex"  : @"1",
                                };
    
    [NetWorkManager requestWithType:HttpRequestTypeGet withMethodName:@"7494/api/Product/GetShopCartListByPage?" withParaments:paraments withSuccessBlock:^(NSDictionary *object) {
        NSLog(@"%@", object);
        if ([object[@"Code"] isEqualToString:@"0"]) {
            [_defaults setObject:[NSString stringWithFormat:@"%@", object[@"TotalCount"]] forKey:@"CartNum"];
        }
    } withFailureBlock:^(NSError *error) {
        NSLog(@"购物车列表请求失败 : %@", error);
    } progress:nil];
}

@end
